import api from './api'
let baseUrl = api.baseUrl.Dev

// loading配置，请求次数统计
function startLoading() {
  wx.showLoading({
    title: 'Loading...',
    icon: 'none'
  })
}

function endLoading() {
  wx.hideLoading();
}

// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;

function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
};

function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
};



module.exports = (url, method, data) => {
  data = data || {};
  wx.showNavigationBarLoading();
  showFullScreenLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: `${baseUrl}/${url}`,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: data,
      method: method,
      success: function (res) {
        if (typeof res.data === "object") {
          if (res.data.status) {
            if (res.data.status === -200) {
              wx.showToast({
                title: "为确保能向您提供最准确的服务，请退出应用重新授权",
                icon: "none"
              });
              reject("请重新登录");
            } else if (res.data.status === -201) {
              wx.showToast({
                title: res.data.msg,
                icon: "none"
              });
              setTimeout(function () {
                wx.navigateTo({
                  url: "/pages/user/user"
                });
              }, 1000);
              reject(res.data.msg);
            }
          }
        }
        resolve(res);
        tryHideFullScreenLoading();
      },
      fail: function (res) {
        // fail调用接口失败
        reject({
          error: '网络错误',
          code: 0
        });
        tryHideFullScreenLoading();
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}